/**
 * Created by zhouxiumin on 2018/6/1.
 * https://www.bootcdn.cn/monaco-editor/
 */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return (r[2]);
    }
    return null;
}

$(document).ready(function () {
    //载入Monaco
    var editor = null;
    require(['vs/editor/editor.main'], function () {
        //得到支持的语言
        var modesIds = monaco.languages.getLanguages().map(function (lang) {
            return lang.id
        }).sort();

        //创建编辑器
        editor = monaco.editor.create(document.getElementById("monaco"), {
            //内容
            value: '',
            //语言
            language: 'xml',
            //自适应调整
            automaticLayout: true,
            //主题，三款：vs、vs-dark、hc-black
            theme: 'vs',
            //代码略缩图
            minimap: {
                enabled: true
            }
        });
        //内容改变事件
        editor.onDidChangeModelContent(function(e){
            console.log(e);
        });
        $.ajax({
            type:"GET",
            url:"/ddcat/api/ddcat.sited.xml?id="+GetQueryString("id"),
            dataType:"text",
            success:function(data){
                editor.setValue(data);
            },
            error:function(jqXHR){
                console.log("Error: "+jqXHR.status);
            }
        });

        $('#save').click(function () {
            console.log('save');
            var xml = editor.getValue();
            var id = $('#xml_id').val();
            $.post('/ddcat/api/modify', {id:id,xml:xml},function (result) {
                $('#result').html(result);
            });
        });

        $('#format').click(function () {
            console.log('format');
            editor.getAction('editor.action.formatDocument').run();
        })
    });
});
